package de.uniulm.muc.mensafinder;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Creates a new sqlite database to save, read and change the username.
 * 
 * @author Adam Just
 */
public class SettingsDbAdapter {

    public static final String KEY_NAME = "name";
    public static final String KEY_ROWID = "_id";

    private static final String TAG = "SettingsDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    
    private static long rowId = -1;

    /**
     * Database creation sql statement
     */
    private static final String DATABASE_CREATE =
        "CREATE TABLE users (_id integer primary key autoincrement, "
        + "name text not null);";

    private static final String DATABASE_NAME = "data";
    private static final String DATABASE_TABLE = "users";
    private static final int DATABASE_VERSION = 2;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS users");
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public SettingsDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the users database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public SettingsDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }


    /**
     * Create a new user using the name provided. If the user is
     * successfully created return the new rowId for that user, otherwise return
     * a -1 to indicate failure.
     * 
     * @param name the name of the user
     * @return rowId or -1 if failed
     */
    public long createUser(String name) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, name);

        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }


    /**
     * Return a Cursor over the list of all users in the database
     * 
     * @return Cursor over all users
     */
    public Cursor fetchAllUsers() {

        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME}, 
        		null, null, null, null, null);
    }

    /**
     * Return a Cursor positioned at the user that matches the given rowId
     * 
     * @param rowId id of user to retrieve
     * @return Cursor positioned to matching user, if found
     * @throws SQLException if user could not be found/retrieved
     */
    public Cursor fetchUser(long rowId) throws SQLException {

        Cursor mCursor =
            mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                    KEY_NAME}, KEY_ROWID + "=" + rowId, null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    /**
     * Update the user using the details provided. The user to be updated is
     * specified using the rowId, and it is altered to use the name
     * value passed in
     * 
     * @param rowId id of user to update
     * @param name value to set username to
     * @return true if the user was successfully updated, false otherwise
     */
    public boolean updateUser(long rowId, String name) {
        ContentValues args = new ContentValues();
        args.put(KEY_NAME, name);

        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
    
    /**
     * Gets the username from the sqlite database
     * @return username saved in db
     */
    public String getUsername() {
    	String result = "";
    	open();
    	
    	Cursor cursor = fetchAllUsers();
    	if (cursor.getCount() == 0) { // no users available
    		close();
    		return result;
    	} else {
    		cursor.moveToLast();
    		result = cursor.getString(cursor.getColumnIndex("name"));
    		rowId = cursor.getLong(cursor.getColumnIndex("_id"));
    	}
    	
    	close();
    	return result;
    }
    
    /**
     * Creates a new username in the users table of the sqlite database
     * @param username
     * @return true, if username was saved
     */
    public boolean saveUsername(String username) {
    	open();
    	rowId = createUser(username);
    	close();
    	
    	if (rowId == -1) { // fails to save user
    		Log.i("MensaFinder", "Cannot save username");
    		return false;
    	}
    	
    	Log.i("MensaFinder", "Username saved");
    	return true;
    }
    
    /**
     * Changes the username of the existing user
     * @param username
     * @return true, if change was successful
     */
    public boolean changeUsername(String username) {
    	boolean result = false;
    	
    	open();
    	if (updateUser(rowId, username)) {
    		Log.i("MensaFinder", "Username changed");
    		result = true;
    	}
    
    	close();
    	return result;
    }
    
    public long getRowId() {
    	return this.rowId;
    }
    
    public void setRowId(long rowId) {
    	this.rowId = rowId;
    }
}

